package com.example.pbj;


import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;




import android.R.color;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;

public class Search extends ListActivity {
	String username = "";
	String question = "";
	String sort = "";
	String cat = "";
	String time = "";
	int idselected = 0;
	
	private static final String PHP_POST = "http://webdev.cs.uwosh.edu/students/meyers11/PHPSearch.php";
	private static final String PHP_VOTES = "http://webdev.cs.uwosh.edu/students/meyers11/PHPVotes.php";
	private static final String PHP_UP = "http://webdev.cs.uwosh.edu/students/meyers11/PHPUpvote.php";
	private static final String PHP_DOWN = "http://webdev.cs.uwosh.edu/students/meyers11/PHPDownvote.php";
	ArrayList<Post> postslist = new ArrayList<Post>();

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_search);
		
		Bundle bundle = this.getIntent().getExtras();
		
		question = bundle.getString("SORTSTRING");
		sort = bundle.getString("SORT");
		cat = bundle.getString("CAT");
		time = bundle.getString("TIME");
		
		if(time.equals("Current Month")){
			time = "2013-07";
		}
		else if(time.equals("August 2013")){
			time = "2013-08";
		}
		else if(time.equals("July 2013")){
			time = "2013-07";
		}
		else if(time.equals("June 2013")){
			time = "2013-06";
		}
		else if(time.equals("May 2013")){
			time = "2013-05";
		}
		
		
		
	
		
	}
	
	@Override
	protected void onResume(){
		super.onResume();
		new search().execute();
		
		
		new getLoginInfo().execute();
		
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.search, menu);
		return true;
	}
	
	@SuppressWarnings("unchecked")
	@Override
	public void onListItemClick(ListView list, View view, int position, long id) {
		super.onListItemClick(list, view, position, id);
		
		HashMap<String, String> hm = new HashMap<String,String>();
		
		hm = (HashMap<String, String>) list.getAdapter().getItem(position);
		
		String subject = hm.get("su");

		for(Post p : postslist){
			if(p.getSubject().equals(subject)){
				
				idselected = p.getId();
				AlertDialog.Builder alert = new AlertDialog.Builder(this);   
				
				LinearLayout lila1= new LinearLayout(this);
			    lila1.setOrientation(1); 
			    final TextView subject2 = new TextView(this); 
			    subject2.setText(subject);
			    final TextView question = new TextView(this);
			    question.setText(p.getQuestion());
			    TextView submitter = new TextView(this);
			    submitter.setText(p.getSubmitter() + "  " + p.getTime());
			    TextView upvotes = new TextView(this);
			    upvotes.setText("Upvotes: " + p.getUpvotes() + "  Downvotes: " + p.getDownvotes());
			    alert.setTitle(subject);  
			    submitter.setTextSize(22);
			    submitter.setTextColor(Color.rgb(113, 46, 128));
			    question.setTextSize(21);
			    submitter.setPadding(15,0,0,15);
			    question.setPadding(15,0,0,10);
			    upvotes.setPadding(15,0,0,5);
			    upvotes.setTextSize(20);
			    //lila1.addView(name2);
			    lila1.addView(submitter);
			    lila1.addView(question);
			    lila1.addView(upvotes);	 
			    alert.setView(lila1);

				alert.setNegativeButton("Close", new DialogInterface.OnClickListener() {
				  public void onClick(DialogInterface dialog, int whichButton) {
					  //Close
				  }
				});
				alert.setPositiveButton("Upvote", new DialogInterface.OnClickListener() {
					  public void onClick(DialogInterface dialog, int whichButton) {
						    int pid = idselected;
						    new upvote().execute(Integer.toString(pid),username);
					  }
					});
				
				alert.setNeutralButton("Downvote", new DialogInterface.OnClickListener() {
					  public void onClick(DialogInterface dialog, int whichButton) {
						    int pid = idselected;
						    new downvote().execute(Integer.toString(pid),username);
					  }
					});

				alert.show();
			}
		}
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		
	    // Handle item selection
	    switch (item.getItemId()) {	
	        case R.id.action_logout:
	        	new Logout().execute();
	        	Intent myIntent3 = new Intent(Search.this, LoginActivity.class);
				startActivityForResult(myIntent3, 0);
				Search.this.finish();
	            return true;
	        case R.id.action_submit:
	        	Intent myIntent4 = new Intent(Search.this, Submit.class);
				startActivityForResult(myIntent4, 0);
				Search.this.finish();
	            return true;
	        default:
	            return super.onOptionsItemSelected(item);
	    }
	}
	
	//Get Login Info
		private class getLoginInfo extends AsyncTask<Void, Void, String>{
			@Override
			protected String doInBackground(Void... nothing) {
				
				PBJDataSource mds2 = new PBJDataSource(Search.this);
				
				mds2.open();
				
				try {
					username = mds2.getUsername();
				} catch (Exception e) {
					e.printStackTrace();
				}
				
				mds2.close();
				
				return username;
			}
			
			@Override
			protected void onPostExecute(String whatever) {
				if (username.equals("user")){
					Intent myIntent = new Intent(Search.this, LoginActivity.class);
					startActivityForResult(myIntent, 0);
					return;
				}
				else{
					return;
				}
			}
			
		}
		
		//get votes
		private class getVotes extends AsyncTask<Integer, Void, ArrayList<Post>>{
			@Override
			protected ArrayList<Post> doInBackground(Integer...params) {
			
				
				ArrayList<Post> posts = new ArrayList<Post>();
				// TODO: attempt authentication against a network service.
				String response = "";
				ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
				NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
				
				if(networkInfo != null && networkInfo.isConnected())
				{
					
					ArrayList<NameValuePair> n = new ArrayList<NameValuePair>(1);
					n.add(new BasicNameValuePair("id", params[0].toString()));
					
					HttpClient httpClient = new DefaultHttpClient();
					HttpPost httppost = new HttpPost(PHP_VOTES);
					try
					{
						httppost.setEntity(new UrlEncodedFormEntity(n));
						ResponseHandler<String> respondHandler = new BasicResponseHandler();
						response = httpClient.execute(httppost, respondHandler);

						//Parse JSON Data
						int upvotes;
						int downvotes;
						

						try{

							JSONArray jArray = new JSONArray(response);
							
							JSONObject json_data = null;

							for(int i = 0; i < jArray.length(); i++)
							{
								json_data = jArray.getJSONObject(i);
								
								upvotes = Integer.parseInt(json_data.getString("upvotes"));
								downvotes = Integer.parseInt(json_data.getString("downvotes"));
								for(Post p: postslist){
									if(p.getId() == params[0]){
										p.setUpvotes(upvotes);
										p.setDownvotes(downvotes);
									}
								}
							}
							
						}catch(JSONException e1){
							e1.printStackTrace();
							System.out.println("HELLO vote JSON error: " + e1);
						}
					}
					catch(Exception e){
						System.out.println("HELLO vote connection error: " + e);
						
					}
				}
			
				return postslist;
			}
			
	        @Override
	        protected void onPostExecute(ArrayList<Post> p) {

	            List<HashMap<String,String>> eList = new ArrayList<HashMap<String,String>>();
	            
	            for(int i=0;i<p.size();i++){
	            	HashMap<String, String> hm = new HashMap<String,String>();
	                hm.put("su",p.get(i).getSubject()); 
	                hm.put("vo","Upvotes: " + p.get(i).getUpvotes() + "  Downvotes: " + p.get(i).getDownvotes()); 
	                hm.put("pic", Integer.toString(R.drawable.purplebull));
	               
	                eList.add(hm);
	            }
	            
	            String[] keys = {"su","vo","pic"};
	            
	            int[] ids = {R.id.subject,R.id.votes,R.id.bullet};
	            
	            SimpleAdapter adapter = new SimpleAdapter(getBaseContext(), eList, R.layout.listview_layout, keys, ids);
	            
	           setListAdapter(adapter);

	        }
			
		}
		
		//upvote
				private class upvote extends AsyncTask<String, String, String>{
					@Override
					protected String doInBackground(String...params) {
					
						
						ArrayList<Post> posts = new ArrayList<Post>();
						// TODO: attempt authentication against a network service.
						String response = "";
						ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
						NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
						
						if(networkInfo != null && networkInfo.isConnected())
						{
							
							ArrayList<NameValuePair> n = new ArrayList<NameValuePair>(1);
							n.add(new BasicNameValuePair("id", params[0]));
							n.add(new BasicNameValuePair("voter", params[1]));
							
							HttpClient httpClient = new DefaultHttpClient();
							HttpPost httppost = new HttpPost(PHP_UP);
							try
							{
								httppost.setEntity(new UrlEncodedFormEntity(n));
								ResponseHandler<String> respondHandler = new BasicResponseHandler();
								response = httpClient.execute(httppost, respondHandler);
							
							}
							catch(Exception e){
								System.out.println("HELLO upvote connection error: " + e);
								
							}
						}
					
						return response;
					}
					
			        @Override
			        protected void onPostExecute(String whatever) {

			            new search().execute();
			        }
					
				}
				
				//downvote
				private class downvote extends AsyncTask<String, String, String>{
					@Override
					protected String doInBackground(String...params) {
					
						
						ArrayList<Post> posts = new ArrayList<Post>();
						// TODO: attempt authentication against a network service.
						String response = "";
						ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
						NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
						
						if(networkInfo != null && networkInfo.isConnected())
						{
							
							ArrayList<NameValuePair> n = new ArrayList<NameValuePair>(1);
							n.add(new BasicNameValuePair("id", params[0]));
							n.add(new BasicNameValuePair("voter", params[1]));
							
							HttpClient httpClient = new DefaultHttpClient();
							HttpPost httppost = new HttpPost(PHP_DOWN);
							try
							{
								httppost.setEntity(new UrlEncodedFormEntity(n));
								ResponseHandler<String> respondHandler = new BasicResponseHandler();
								response = httpClient.execute(httppost, respondHandler);
							
							}
							catch(Exception e){
								System.out.println("HELLO downvote connection error: " + e);
								
							}
						}
					
						return response;
					}
					
			        @Override
			        protected void onPostExecute(String whatever) {

			            new search().execute();
			        }
					
				}
		
		//Search
		private class search extends AsyncTask<Void, Void, ArrayList<Post>>{
			@Override
			protected ArrayList<Post> doInBackground(Void... nothing) {
				
				ArrayList<Post> posts = new ArrayList<Post>();
				// TODO: attempt authentication against a network service.
				String response = "";
				ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
				NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
				
				if(networkInfo != null && networkInfo.isConnected())
				{
					
					ArrayList<NameValuePair> n = new ArrayList<NameValuePair>(1);
					n.add(new BasicNameValuePair("question", question));
					n.add(new BasicNameValuePair("cat", cat));
					n.add(new BasicNameValuePair("sort", sort));
					n.add(new BasicNameValuePair("time", time));
					
					HttpClient httpClient = new DefaultHttpClient();
					HttpPost httppost = new HttpPost(PHP_POST);
					try
					{
						httppost.setEntity(new UrlEncodedFormEntity(n));
						ResponseHandler<String> respondHandler = new BasicResponseHandler();
						response = httpClient.execute(httppost, respondHandler);

						//Parse JSON Data
						int sid;
						String subject = "";
						String question = "";
						String submitter = "";
						String time = "";

						try{

							JSONArray jArray = new JSONArray(response);
							
							JSONObject json_data = null;

							for(int i = 0; i < jArray.length(); i++)
							{
								json_data = jArray.getJSONObject(i);
								
								subject = json_data.getString("subject");
								submitter = json_data.getString("submitter");
								sid = Integer.parseInt(json_data.getString("sid"));
								time = json_data.getString("time");
								question = json_data.getString("question");
													
								Post p = new Post(sid,question,subject,submitter,time,0,0);
								posts.add(p);
							}
							
						}catch(JSONException e1){
							e1.printStackTrace();
							System.out.println("HELLO search JSON error: " + e1);
						}
					}
					catch(Exception e){
						System.out.println("HELLO connection error: " + e);
						
					}
				}
				
				postslist = posts;
				return posts;
			}
			
	        @Override
	        protected void onPostExecute(ArrayList<Post> p1) {
	        	
	        	
	    		for(Post p2 : p1){
	    			new getVotes().execute(p2.getId());
	    		}
	        }
			
		}
		
		//Logout
		private class Logout extends AsyncTask<Void, Void, String>{
			@Override
			protected String doInBackground(Void... nothing) {
				
				PBJDataSource mds2 = new PBJDataSource(Search.this);
				
				mds2.open();
				
				try {
					mds2.logoutUser();
				} catch (Exception e) {
					e.printStackTrace();
				}
				
				mds2.close();
				
				return "";
			}
			
			@Override
			protected void onPostExecute(String whatever) {
					Intent myIntent = new Intent(Search.this, LoginActivity.class);
					startActivityForResult(myIntent, 0);
					Search.this.finish();
			}
			
		}

}
